--
-- WALLCLOCK.LUA
--
-- Sample program for Lua Lanes
--

require "lanes"

local TUNE_AT=10.0  -- seconds

print [[

*** Wall clock sample ***

'Now' times should balance to being even ]]..TUNE_AT..[[ seconds.

]]

local linda= lanes.linda()

-- Immediate timer; to get things started
--
lanes.timer( linda, "tick", 0.0, TUNE_AT )

-- Loop, adjusting on the go
--
while true do
    local secs= linda.receive("tick")
    local adj= TUNE_AT - (secs % TUNE_AT)
    
    -- Better miss a beat than try too small adjustment 
    -- (this should happend only on the first loop)
    --
    if adj<=1.0 then
        adj= adj+TUNE_AT
    end
    
    if math.abs(adj - TUNE_AT) < 0.5 then
        -- Adjusting the timer, so we get nearer to wall clock
        --
        lanes.timer( linda, "tick", adj, TUNE_AT )
        
        print( "Adjusted timer: %.2f", adj )
    end

    print( string.format("Now: %.2f secs", secs) )
end
